package com.zhonghan.recharge.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageInfo;
import com.zhonghan.common.bean.Result;
import com.zhonghan.common.enums.ResultStatus;
import com.zhonghan.common.utils.ExcelUtils;
import com.zhonghan.common.utils.StringUtils;
import com.zhonghan.recharge.pojo.GascardInfo;
import com.zhonghan.recharge.pojo.ZhBusinessRecord;
import com.zhonghan.recharge.pojo.ZhBusinessUser;
import com.zhonghan.recharge.pojo.ZhCardReceive;
import com.zhonghan.recharge.pojo.ZhFillCard;
import com.zhonghan.recharge.pojo.ZhGascardOrder;
import com.zhonghan.recharge.service.GascardInfoService;
import com.zhonghan.recharge.service.OilCustomerOrderService;
import com.zhonghan.recharge.service.ZhBusinessGascardOrderService;
import com.zhonghan.recharge.service.ZhBusinessRecordService;
import com.zhonghan.recharge.service.ZhBusinessUserService;
import com.zhonghan.recharge.service.ZhCardReceiveService;
import com.zhonghan.recharge.service.ZhFillCardService;
import com.zhonghan.recharge.service.ZhGascardOrderService;

/**
 * 后台管理控制层
 * 
 * @author zhangceven
 *
 */
@RequestMapping("/admin")
@Controller
public class AdminController {

	private Logger logger = Logger.getLogger(AdminController.class);

	@Autowired
	private ZhGascardOrderService zhGascardOrderService;

	@Autowired
	private ZhFillCardService zhFileCardService;

	@Autowired
	private GascardInfoService gasCardInfoService;

	@Autowired
	private ZhCardReceiveService zhCardReceiveService;
	
	@Autowired
	private ZhBusinessUserService zhBusinessUserService;
	
	@Autowired
	private ZhBusinessRecordService zhBusinessRecordService;
	
	@Autowired
	private ZhBusinessGascardOrderService zhBusinessGascardOrderService;
	
	@Autowired
	private OilCustomerOrderService oilCustomerOrderService;
	/**
	 * 跳转到订单查询页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/order/get", method = RequestMethod.GET)
	public String showOrder() {
		return "admin/order";
	}

	/**
	 * 返回后台查询订单数据
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/order/get", method = RequestMethod.POST)
	@ResponseBody
	public Result order(HttpServletRequest request, HttpServletResponse response, String orderNo, String gascardNo,
			String telephone, String fillCardSequence, String rechargeState, String beginTime, String endTime,
			String orderType, Integer pageNum, Integer pageSize) {

		pageSize = pageSize == null ? 10 : pageSize;
		Result result = zhGascardOrderService.selectZhGascardOrderByCondition(orderNo, gascardNo, telephone,
				fillCardSequence, rechargeState, beginTime, endTime, orderType, pageNum, pageSize);

		return result;
	}

	/**
	 * 导出订单表
	 * 
	 * @param request
	 * @param response
	 * @param orderNo
	 * @param gascardNo
	 * @param telephone
	 * @param fillCardSequence
	 * @param rechargeState
	 * @param beginTime
	 * @param endTime
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/order/export")
	public void exportOrder(HttpServletRequest request, HttpServletResponse response, String orderNo, String gascardNo,
			String telephone, String fillCardSequence, String rechargeState, String beginTime, String endTime,
			String orderType) {

		Result result = zhGascardOrderService.selectZhGascardOrderByCondition(orderNo, gascardNo, telephone,
				fillCardSequence, rechargeState, beginTime, endTime, orderType, 0, 0);
		PageInfo<ZhGascardOrder> pageInfo = null;
		if (result != null) {
			pageInfo = (PageInfo<ZhGascardOrder>) result.getData();
		}
		List<ZhGascardOrder> list = pageInfo.getList();

		String[] headerColumns = { "orderNo", "fillCardSequence", "gascardNo", "fillName", "telephone", "bmItemName",
				"facePrice", "orderTime", "rechargeState" };
		String[] titleName = { "订单编号", "充值卡卡号", "油卡卡号", "姓名", "电话", "商品名称", "面额", "时间", "订单状态" };

		ExcelUtils e = new ExcelUtils(request, response,
				"订单明细表" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()), "订单明细");
		e.setTitle("订单明细", 8);
		e.setHeader(titleName);
		e.export(headerColumns, list);
		System.out.println("导出成功");
		logger.info("订单导出成功!");
	}

	/**
	 * 跳转到充值卡查询页面
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/card/get", method = RequestMethod.GET)
	public String showCard(HttpServletRequest request, HttpServletResponse response, Model model) {

		return "admin/card";
	}

	/**
	 * 返回后台查询充值卡数据
	 * 
	 * @param sequence
	 *            充值卡序列号
	 * @param status
	 *            试用状态
	 * @param facePrice
	 *            面额
	 * @param pageNum
	 *            当前页
	 * @param pageSize
	 *            每页显示条数
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/card/get", method = RequestMethod.POST)
	@ResponseBody
	public Result FileCardByCardNo(String sequence, Integer statusName, Integer facePrice, Integer pageNum,
			Integer pageSize, String beginTime, String endTime, Model model) {
		Result result = zhFileCardService.selectCardList(sequence, statusName, facePrice, beginTime, endTime, pageNum,
				pageSize);
		return result;
	}

	/**
	 * 导出数据
	 * 
	 * @param request
	 *            充值卡卡号
	 * @param response
	 * @param sequence
	 * @param status
	 *            充值卡状态
	 * @param facePrice
	 *            面额
	 * @param pageNum
	 * @param pageSize
	 * @param beginTime
	 * @param endTime
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/card/export")
	public void exportOrder(HttpServletRequest request, HttpServletResponse response, String sequence,
			Integer statusName, Integer facePrice, Integer pageNum, Integer pageSize, String beginTime,
			String endTime) {

		Result result = zhFileCardService.selectCardList(sequence, statusName, facePrice, beginTime, endTime, 0, 0);
		PageInfo<ZhFillCard> pageInfo = null;

		if (result != null) {
			pageInfo = (PageInfo<ZhFillCard>) result.getData();
		}
		List<ZhFillCard> list = pageInfo.getList();

		String[] headerColumns = { "sequence", "statusName", "facePrice", "consumeTime", "outPrice", "overdueTime",
				"createrTime" };
		String[] titleName = { "卡号", "充值卡状态", "面额", "消费时间", "售出价", "创建时间", "过期时间" };

		ExcelUtils e = new ExcelUtils(request, response, "充值卡明细表", "卡明细");
		e.setTitle("充值卡明细", 8);
		e.setHeader(titleName);
		e.export(headerColumns, list);
	}

	/**
	 * 跳转油卡管理
	 * 
	 * @return
	 */
	@RequestMapping(value = "/gasCard/get", method = RequestMethod.GET)
	public String updateGasCard() {
		return "admin/gasCard";
	}

	/**
	 * 通过卡号查询
	 * 
	 * @param cardNo
	 *            油卡号
	 * @param model
	 * @return
	 */
	@RequestMapping("/gasCardByCardNo")
	public String updateGasCardUpdate(String cardNo, Model model) {
		List<GascardInfo> selectGascardInfoByCardNo = gasCardInfoService.selectGascardInfoByCardNo(cardNo);
		model.addAttribute("cardNo", cardNo);
		model.addAttribute("gasCard", selectGascardInfoByCardNo);
		return "admin/gasCard";
	}

	/**
	 * 通过id去修改试用次数
	 * 
	 * @param id
	 *            油卡的id
	 * @return
	 */
	@RequestMapping("/gasCardUpdate")
	public String gasCardUpdate(Integer id) {
		gasCardInfoService.updateGascardInfoByIds(id);
		// 保存日志信息

		// 拿到油卡号
		GascardInfo selectGascardInfoById = gasCardInfoService.selectGascardInfoById(id);
		String cardNo = selectGascardInfoById.getCardNo();
		return "redirect:gasCardByCardNo?cardNo=" + cardNo;
	}

	/**
	 * 通过id删除
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/gasCardDelete")
	public String gasCardDelete(Integer id) {
		gasCardInfoService.deleteGascardInfoById(id);
		return "admin/gasCard";
	}

	/**
	 * 查询订单详情
	 * 
	 * @param request
	 * @param response
	 * @param orderNo
	 * @return
	 */
	@RequestMapping("/order/detail")
	@ResponseBody
	public Result getOrderDetail(HttpServletRequest request, HttpServletResponse response, String orderNo) {

		Result result = zhGascardOrderService.getOrderDetail(orderNo);

		return result;
	}

	/**
	 * 跳转到领取界面
	 * 
	 * @return
	 */
	@RequestMapping(value="/receive",method= RequestMethod.GET)
	public String receive() {
		return "admin/receive";
	}

	/**
	 * 添加领取数据
	 * 
	 * @param sequenceBegin
	 *            充值卡开始卡号
	 * @param sequenceEnd
	 *            充值卡结束卡号
	 * @param sequenceTime
	 *            领取时间
	 * @param receiveName
	 *            领取人
	 * @param receiveCount
	 *            领取数量
	 * @param facePrice
	 *            面额
	 * @return
	 */
	@RequestMapping("/addReceiver")
	@ResponseBody
	public Result gasCardBySequenceAdd(String sequenceBegin, String sequenceEnd, String receiveName,
			Integer receiveCount, Integer facePrice) {

		Result result = zhCardReceiveService.addReceiver(sequenceBegin,sequenceEnd,receiveName,receiveCount,facePrice);
		
		return result;
	}
	/**
	 * 跳转所有领卡人的页面
	 * @return
	 */
	@RequestMapping(value="/receiveAll",method=RequestMethod.GET)
	public String toReceive(){
		return "admin/receives";
	}
	/**
	 * 查询所有领取人
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/receiveAll",method= RequestMethod.POST)
	@ResponseBody
	public Result receiverAll(Model model,String reciveName,Integer pageNum,Integer pageSize,String beginTime,String endTime){
		Result result = zhCardReceiveService.selectZhCardReceiveByName(reciveName,beginTime,endTime,pageNum, pageSize);
		
		return result;
	}
	
	/**
	 * 导出领卡人
	 * @param reciveName
	 * @param beginTime
	 * @param endTime
	 */
	@RequestMapping(value="/exportReceiver")
	public void exportReceiver(HttpServletRequest request,HttpServletResponse response,String reciveName,String beginTime,String endTime){
		
		Result result = zhCardReceiveService.selectZhCardReceiveByName(reciveName, beginTime, endTime, 0, 0);
		
		PageInfo<ZhCardReceive> pageInfo = null;
		if (result != null) {
			pageInfo = (PageInfo<ZhCardReceive>) result.getData();
		}
		List<ZhCardReceive> list = pageInfo.getList();

		String[] headerColumns = { "receiveName", "sequenceBegin","sequenceEnd","facePrice", "receiveCount",
				"useCards", "sequenceTime"};
		String[] titleName = {"领取人", "领取卡号的开始卡号","领取卡号的结束卡号","领取的卡的面额", "数量", "已使用数量", "领取时间"};

		ExcelUtils e = new ExcelUtils(request, response,
				"领卡人列表" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()), "领卡人明细");
		e.setTitle("领卡人明细", 7);
		e.setHeader(titleName);
		e.export(headerColumns, list);
		
		logger.info("领卡人明细导出成功!");
		
	}
	
	
	
	/**
	 * 跳转查看领卡人
	 * 
	 * @return
	 */
	@RequestMapping("/receiver")
	public String getReceiver() {

		return "admin/receiver";
	}

	/**
	 * 查询充值卡
	 * 
	 * @param sequence
	 *            充值卡卡号
	 * @return
	 */
	@RequestMapping("/gasCardReceiver")
	public String gasCardReceiver(String sequence, Model model) {
		ZhCardReceive selectZhCardReceiveBySequence = zhCardReceiveService
				.selectZhCardReceiveBySequence(sequence);
		model.addAttribute("receive", selectZhCardReceiveBySequence);
		model.addAttribute("sequence", sequence);
		return "admin/receiver";
	}
	
	/**
	 * 跳转余额充值
	 * @return
	 */
	@RequestMapping(value="/businessToRecharge",method=RequestMethod.GET)
	public String toSumRecharge(String userId,Model model){
		
		ZhBusinessUser businessUser = zhBusinessUserService.selectZhBusinessUserById(Long.valueOf(userId));
		if(businessUser != null){
			model.addAttribute("businessUser", businessUser);
			
			return "admin/sumRecharge";
		}else{
			//操作错误
			return "admin/login";
		}	

	}
	/**
	 * 余额充值
	 * @return
	 */
	@RequestMapping(value="/sumRecharger",method=RequestMethod.POST)
	@ResponseBody
	public Result sumRecharger(HttpServletRequest request,HttpServletResponse response,Long totalAssets,String phone,Long businessId){
		Result result = new Result();
		try {
			//添加充值记录
			ZhBusinessRecord record =new ZhBusinessRecord();
			record.setMessage("充值");
			record.setOperationType("1");
			record.setRechargeMoney(totalAssets);
			record.setRechargeTime(new Date());
			record.setUserId(businessId);
			int num = zhBusinessRecordService.insertZhBusinessRecord(record);
			if(num >= 0){
				//修改余额/累加 余额
				zhBusinessUserService.updateZhBusinessUserByTotalAssets(totalAssets, phone);
			}
			result.setCode("1");
			result.setMsg("充值成功");
		}catch(Exception e){
			logger.info(e.getMessage());
			result.setCode("0");
			result.setMsg("充值失败");
		}
		return result;
		//return "redirect:/admin/bigCustomer";
	}

	/**
	 * 查看所有的大客户
	 * @param model
	 * @return
	 */
	@RequestMapping("/bigCustomer")
	public String selectbigCustomer(Model model){
		List<ZhBusinessUser> selectZhBusinessUser = zhBusinessUserService.selectZhBusinessUser();
		model.addAttribute("selectZhBusinessUser", selectZhBusinessUser);
		return "admin/bigCustomer";
	}
	/**
	 * 查看充值纪录
	 * @param id
	 * @param model
	 * @return
	 */
//	@RequestMapping("/sumRechargerRecord")
//	public String selectBusiness(Long id,Model model){
//		//ZhBusinessRecord selectZhBusinessRecordById = zhBusinessRecordService.selectZhBusinessRecordById(id);
//		ZhBusinessRecord record = new ZhBusinessRecord();
//		record.setUserId(id);
//		List<ZhBusinessRecord> selectZhBusinessRecordByUserId = zhBusinessRecordService.selectZhBusinessRecordByUserId(id);
//		ZhBusinessUser selectZhBusinessUserById = zhBusinessUserService.selectZhBusinessUserById(id);
//		
//		model.addAttribute("name", selectZhBusinessUserById);
//		model.addAttribute("BusinessOrder", selectZhBusinessRecordByUserId);
//		return "admin/businessRecord";
//	}
	
	/**
	 * 后台管理注册商户账号页面
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/register/business")
	public String showRegisterBusiness(HttpServletRequest request,HttpServletResponse response){
		
		return "admin/registerBusiness";
	}
	
	/**
	 * 后台管理注册商户账号
	 * @param request
	 * @param response
	 * @param nickname
	 * @param telephone
	 * @param password
	 * @return
	 */
	@RequestMapping(value="/register/business",method=RequestMethod.POST)
	@ResponseBody
	public Result registerBusiness(HttpServletRequest request,HttpServletResponse response,String nickname,String phone,String password){
		Result result = new Result();
		ZhBusinessUser value = new ZhBusinessUser();
		value.setTotalAssets(0L);
		value.setCreateTime(new Date());
		value.setDeleted(0);
		if(StringUtils.isNotEmpty(nickname)){
			value.setNickname(nickname);
		}else{
			result.setCode(ResultStatus.FAILURE.getCode());
			result.setMsg("昵称不能为空");
			return result;
		}
		if(StringUtils.isNotEmpty(phone)){
			value.setPhone(phone);
		}else{
			result.setCode(ResultStatus.FAILURE.getCode());
			result.setMsg("手机号不能为空");
			return result;
		}
		if(StringUtils.isNotEmpty(password)){
			value.setPassword(StringUtils.md5EncryptWithSalt(password, "zhonghan"));
		}else{
			result.setCode(ResultStatus.FAILURE.getCode());
			result.setMsg("密码不能为空");
			return result;
		}
		try {
			zhBusinessUserService.insertNonEmptyZhBusinessUser(value );
			result.setCode(ResultStatus.SUCCESS.getCode());
			result.setMsg("账号添加成功!");
			
			return result;
		} catch (Exception e) {
			result.setCode(ResultStatus.BUSYNESS.getCode());
			result.setMsg(ResultStatus.BUSYNESS.getDescription());
			e.printStackTrace();
		}
		
		return null;
		
	}
	
	/**
	 * 后台查询商户订单页面
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/order/business/get",method=RequestMethod.GET)
	public String showBusinessOrder(HttpServletRequest request,HttpServletResponse response,Model model){
		
		List<ZhBusinessUser> businessList = zhBusinessUserService.selectZhBusinessUser();
		
		model.addAttribute("Business", businessList);
		
		return "admin/businessOrder";
	}
	
	/**
	 * 查看商户订单
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/order/business/get")
	@ResponseBody
	public Result showBusinessOrder(HttpServletRequest request,HttpServletResponse response,Long businessId,String orderNo,String gascardNo,
			String telephone, String fillCardSequence, String rechargeState, String beginTime, String endTime,
			String orderType, Integer pageNum, Integer pageSize) {
		
		Result result = zhBusinessGascardOrderService.selectZhBusinessGascardOrderByCondition(businessId, orderNo, gascardNo, telephone, fillCardSequence, rechargeState, beginTime, endTime, orderType, pageNum, pageSize);
		
		return result;
	}

	/**
	 * 后台管理商户导出订单表
	 * 
	 * @param request
	 * @param response
	 * @param orderNo
	 * @param gascardNo
	 * @param telephone
	 * @param fillCardSequence
	 * @param rechargeState
	 * @param beginTime
	 * @param endTime
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/order/business/export")
	public void exportBusinessOrder(HttpServletRequest request, HttpServletResponse response,Long businessId, String orderNo, String gascardNo,
			String telephone, String fillCardSequence, String rechargeState, String beginTime, String endTime, String orderType) {

		Result result = zhBusinessGascardOrderService.selectZhBusinessGascardOrderByCondition(businessId,orderNo, gascardNo, telephone,
				fillCardSequence, rechargeState, beginTime, endTime, orderType, 0, 0);
		PageInfo<ZhGascardOrder> pageInfo = null;
		if (result != null) {
			pageInfo = (PageInfo<ZhGascardOrder>) result.getData();
		}
		List<ZhGascardOrder> list = pageInfo.getList();

		String[] headerColumns = { "orderNo", "gascardNo","fillName","telephone", "bmItemName",
				"facePrice", "orderTime", "rechargeState" };
		String[] titleName = { "订单编号", "油卡卡号","姓名","电话", "商品名称", "面额", "时间", "订单状态" };

		ExcelUtils e = new ExcelUtils(request, response,
				"订单明细表" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()), "订单明细");
		e.setTitle("订单明细", 8);
		e.setHeader(titleName);
		e.export(headerColumns, list);
		
		logger.info("订单导出成功!");
	}
	/**
	 * 买油送油 买油送车 
	 */
	
	/**
	 * 跳转到买油送车页面
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/business/oilCar")
	public String showOilCar(HttpServletRequest request, HttpServletResponse response){
		
		
		return "admin/oilCar";
		
	}
	
	/**
	 * 显示分期返现页面
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/business/cashback")
	public String showCashback(HttpServletRequest request, HttpServletResponse response,Integer id,Model model){
		
		model.addAttribute("ID", id);
		
		return "admin/cashback";
		
	}
	/**
	 * 跳转查看充值纪录
	 * @return
	 */
	@RequestMapping(value="sumRechargerRecord",method=RequestMethod.GET)
	public String rechargeRecord(Long id,Model model){
		model.addAttribute("id",id);
		return "admin/businessRecord";
	}
	/**
	 * 查看对应店铺的充值纪录
	 * @param id 店铺的id
	 * @param beginTime 开始时间
	 * @param endTime 结束时间
	 * @param pageNum 
	 * @param pageSize
	 * @return
	 */
	@RequestMapping(value="sumRechargerRecord",method=RequestMethod.POST)
	@ResponseBody
	public Result rechargeRecordByTime(Long id,String beginTime, String endTime,Integer pageNum, Integer pageSize){
		pageSize = pageSize == null ? 10 : pageSize;
		Result result = zhBusinessRecordService.selectZhBusinessRecordByTime(id, beginTime, endTime, pageNum, pageSize);
		return result;
	}
}
